<script setup lang="ts">
/**
 * @title -房屋抵押
 * @author -qqz
 * @date -2024/3/19
 */
import {onMounted, ref} from "vue";
import {applicationLoan, getProductInfo, uploads} from "@/api/apply.ts";
import CustomIDCardUploader from "@/components/CustomIDCardSelect.vue";
import {hideTextAtIndex} from "@pureadmin/utils";
import {UserPreferenceStore} from "@/utils/UserPreferenceStore.ts";
import {useCascaderAreaData} from '@vant/area-data';
import {useRouter} from "vue-router";

const cascaderValue = ref('');
const show = ref(false);
const uploaderConfig = ref({
  frontBackground: new URL('../../../assets/image/ico_certificate.png', import.meta.url).href,
  backBackground: new URL('../../../assets/image/ico_certificate.png', import.meta.url).href
  ,
  txt1: '房产证上传',
  txt2: '其他证件'
})

/**
 * 上传身份证正面
 * @param file 文件
 */
const uploadIDCardFront = (file: any) => {
  // console.log(file);
  console.log(file.file);
  // console.log(file.content);
  formSubmit.value.toDoUploadFileList.push(file.file)
}

/**
 * 身份证反面
 * @param file 文件
 */
const uploadIDCardBack = (file: any) => {
  formSubmit.value.toDoUploadFileList.push(file.file)
}

const options = useCascaderAreaData();

const onFinish = ({selectedOptions}: any) => {
  show.value = false;
  formSubmit.value.address = selectedOptions.map((option: any) => option.text).join('/');
};
const router = useRouter();
/**
 * 提交表单
 * @param values 提交表单数据
 */
const onSubmit = async () => {

  if (formSubmit.value.toDoUploadFileList.length != 0) {

    // 组装文件上传参数
    const formData = new FormData();
    Array.from(formSubmit.value.toDoUploadFileList).forEach((file: any) => {
      formData.append('files', file);
    });

    //  多个文件上传
    const uploadResult: any = await uploads(formData)

    formSubmit.value.imageUrl = uploadResult.data.data[0].fileName
    //  如果上传了身份证反面
    if (uploadResult.data.data.length >= 2) {
      formSubmit.value.imageUrlB = uploadResult.data.data[1].fileName
    }
  }

  let json = {
    "applicationId": 0,
    "productId": 3,
    "loanAmount": 0.0,
    "productName": 'productData.value?.productName',
    "productType": 'productData.value?.productType'
  }
  applicationLoan(json).then((res) => {
    console.log(res);
    router.push({name: 'succeed'})
  })


  //  提交表单数据
  // const submitResult = await applicationLoan(formSubmit.value)
  // console.log(submitResult);
  // showToast({message: submitResult.msg});
  // // 回到申请页面
  // setTimeout(() => {
  //   router.push({name: 'index'})
  // }, 1200)
};

onMounted(() => {
  let phone = UserPreferenceStore.getInstance().getPhone();
  formSubmit.value.phone = hideTextAtIndex(phone, {start: 3, end: 6});
  // 查找产品信息
  getProductInfo({productId: 3}).then((res) => {
    formSubmit.value.productInfo = res.data;
    console.log(formSubmit.value);
  })
})


export interface RootObjectDataProduct {
  productId: number;
  interestRate: number;
  loanTerm: number;
  requirements: string;
  description: string;
  validityPeriod: number;
  "phone": string,
  "address": string,
  "imageUrlB": string,
  "imageUrl": string,
  "loanAmount": 0,
  "toDoUploadFileList": File[],
  productInfo: any
}


const formSubmit = ref<RootObjectDataProduct>({
  "phone": "",
  "productId": 0,
  "loanAmount": 0.0,
  "address": '',
  loanTerm: 0,
  imageUrl: '',
  imageUrlB: "",
  toDoUploadFileList: [],
  interestRate: 9,
  requirements: "",
  description: "",
  validityPeriod: 0,
  productInfo: {}
});


</script>

<template>
  <div id="index">

    <!--  资料填写(房)  -->

    <!--  仿制页面  -->
    <!-- https://api.jr.mi.com/loan/loanh5/market.html?from=mifi&_transparentNaviBar=true&_darkBg=true#/third/house/applyNew  -->

    <img style="width: 100%;position: relative"
         src="../../../assets/image/house/ico_bg.png">

    <img style="width: 70%;height: 61px; position: absolute;top: 10%; left: 4%"
         src="../../../assets/image/house/ico_qyzx.png">

    <!--    <img style="width: 70%; position: absolute;top: 31%;left: 0"-->
    <!--         src="https://ts.market.mi-img.com/thumbnail/png/q80/Finance/0bd8d5228974045208687f8d233443156700c788b"> -->
    <!--    -->
    <img style="width: 70%;height: 95.27px; position: absolute;top: 31%;left: 0"
         src="../../../assets/image/house/ico_6000.png">


    <div class="overlay-div ">
      <van-form @submit="onSubmit">
        <!--  inset 这个其实是一个圆角样式属性 -->
        <van-cell-group class="card">
          <van-field
              name="姓名"
              label="姓名"
              placeholder="姓名"
          />
          <van-field v-model="formSubmit.phone" maxlength="11" disabled label="手机号" placeholder="请输入手机号"/>

          <van-field
              name="申请金额"
              v-model="formSubmit.loanAmount"
              label="申请金额"
              placeholder="申请金额"
          />
          <van-field
              name="房产位置"
              label="房产位置"
              v-model="formSubmit.address"
              is-link
              readonly
              @click="show = true"
              placeholder="房产位置"
          />

          <van-button size="large"
                      round block
                      type="success"
                      native-type="submit">
            立即申请
          </van-button>

          <p class="org">由建设银行、泛华金融为您提供服务</p>

        </van-cell-group>


        <div class="card" style="text-align: center;margin-top: 12px;padding-bottom: 25px;padding-top:25px;">
          <span>申请流程</span>
          <img class="header-img"
               src="../../../assets/image/house/ico_flow.png">
        </div>

        <div class="card" style="margin-top: 12px;">
          <div style="display: flex;flex-direction: column;text-align: center;padding: 12px;">
            <span style="color: #CCA872;">产品介绍</span>
            <p
                style="
                  text-align: left;
        font-size: .74667rem;
        color: #333;
        letter-spacing: 0;
        padding: 0.2rem 1.65333rem 0.200rem;">

              企业主专享房抵贷服务是由鑫盛源和机构联合推出的房屋抵押贷款服务，产品年化利率低，期限长，随借随还
              产品服务覆盖全国30+城市，服务于拥有房产的企业主、个体工商户经营者等，为您解决大额资金周转问题。
            </p>
          </div>
        </div>


        <!-- 上传控件 -->
        <CustomIDCardUploader
            style="display: flex;flex-direction: column;align-items: center;margin-top: 20px;margin-bottom: 12px;"
            v-show="false"
            :description-txt-a="uploaderConfig.txt1"
            :description-txt-b="uploaderConfig.txt2"
            :cardFrontBackground="uploaderConfig.frontBackground"
            :cardBackBackground="uploaderConfig.backBackground"
            :frontCallBack="uploadIDCardFront"
            :backCallBack="uploadIDCardBack">
        </CustomIDCardUploader>

      </van-form>
    </div>

    <van-popup v-model:show="show" round position="bottom">
      <van-cascader
          v-model="cascaderValue"
          title="请选择所在地区"
          :options="options"
          @close="show = false"
          @finish="onFinish"
      />
    </van-popup>

  </div>
</template>

<style scoped>

#index {
  width: 100%;
  position: relative;
  display: inline-block;
}

.logo {
  position: absolute;
  top: 10%;
  width: 100%;
}

.overlay-div {
  position: absolute;
  top: 56.5%;
  left: 50%;
  width: 92%;
  height: 100%;
  transform: translateX(-50%) translateY(5%);
}


/* 头部容器样式 */
.header-container {
  text-align: center; /* 让内部元素居中对齐 */
}

/* 图片样式 */
.header-img {
  width: 90%;
  padding-top: 15px;
}

/* 文字样式 */
.header-text {
  margin-top: 0.57333rem; /* 调整文字与图片之间的间距，根据实际需求调整 */
  color: #333; /* 设置文字颜色，根据实际需求调整 */
  font-size: .84rem;
}

.org {
  color: rgba(19, 30, 93, .5);
  font-size: .60556rem;
  text-align: center;
}


/************************************ vant3上传组件样式start *********************************/

:deep(.van-uploader__upload) {
  width: 90vw !important;
  height: 150px !important;
}

:deep(.van-uploader__preview-image) {
  width: 90vw !important;
  height: 150px !important;
}

/************************************ vant3上传组件样式end *********************************/

.van-button {
  background-image: linear-gradient(63.78deg, #3d73f2 16.5%, #0163ff 83.5%);
}

</style>
